
//
//  NHTTPManage.m
//  News
//
//  Created by zhangtao on 2018/11/8.
//  Copyright © 2018 zt.td. All rights reserved.
//

#import "NHTTPManage.h"

@implementation NHTTPManage


+(id)shareInstance{
    static NHTTPManage *manage = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        manage = [[self alloc]init];
    });
    return manage;
}

-(void)afGet:(NSString *)url andParam:(NSDictionary *)param success:(LCSuccessHandler)success failture:(LCErrorHandler)failture{
    
    NSLog(@"url:%@ \n param:%@",url,param);
    
    NSString *urlStr = [baseUrl stringByAppendingString:url];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
    [manager GET:urlStr parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        //
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
//        NSLog(@"%@",dic);
        NSLog(@"responseString:\n%@",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
        if ([dic[@"RetCode"] intValue] == 0 && [dic[@"Success"] intValue] == 1) {
            success(dic);
        }else{
            failture(dic[@"Msg"]? :@"");
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        failture(@"网络请求失败");
    }];
}


-(void)afPOST:(NSString *)url andParam:(NSDictionary *)param success:(LCSuccessHandler)success failture:(LCErrorHandler)failture{
    
    //    [[MBProgressController sharedInstance] showWithText:@""];
    NSString *urlStr = [baseUrl stringByAppendingString:url];
    
    AFHTTPSessionManager *manage = [AFHTTPSessionManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    manage.requestSerializer = [AFHTTPRequestSerializer serializer];
    manage.requestSerializer.timeoutInterval = 30;
    if (TOKEN) {
        [manage.requestSerializer setValue:TOKEN forHTTPHeaderField:@"Token"];
    }
    
    [manage POST:urlStr parameters:param
        progress:^(NSProgress * _Nonnull uploadProgress) {
            //
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            NSLog(@"responseString:\n%@",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
            if ([dic[@"Success"] boolValue] == YES) {
                success(dic);
                
            }else{
                failture(dic[@"Msg"]? :@"");
                //                failture(@"failture");
            }
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            failture(@"网络请求失败");
        }];
}


-(void)uploadImagesWithUrl:(NSString *)url andImages:(NSArray *)images andParam:(NSDictionary *)param success:(LCSuccessHandler)success fail:(LCErrorHandler)fail{
    NSString *urlStr = [baseUrl stringByAppendingString:url];
    
    
    UIImage *iamge = images.firstObject;
    NSData *imageData = UIImageJPEGRepresentation(iamge,1.0);
    
  
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlStr parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        //        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
        [formData appendPartWithFileData:imageData name:@"userlogo" fileName:@"filename.jpg" mimeType:@"image/jpeg"];
    } error:nil];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSURLSessionUploadTask *uploadTask;
    uploadTask = [manager
                  uploadTaskWithStreamedRequest:request
                  progress:^(NSProgress * _Nonnull uploadProgress) {
                      // This is not called back on the main queue.
                      // You are responsible for dispatching to the main queue for UI updates
                      dispatch_async(dispatch_get_main_queue(), ^{
                          //Update the progress view
                          //                          [progressView setProgress:uploadProgress.fractionCompleted];
                      });
                  }
                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                      if (error) {
                          
                      } else {
                          
                          NSDictionary *dic = responseObject;
                          if ([dic[@"status"] intValue] == 200) {
                              success(dic);
                          }else{
                              UIWindow *win = [UIApplication sharedApplication].keyWindow;
                              [win makeToast:responseObject[@"message"] duration:1 position:CSToastPositionCenter];
                          }
                          //[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                          NSLog(@"%@ %@", response, responseObject);
                      }
                  }];
    
    [uploadTask resume];
}


-(NSData *)reSizeImage:(UIImage *)sourceImage maxSizeWithKB:(CGFloat)maxSize{
    if (maxSize <= 0.0) maxSize = 1024.0;
    
    NSData *imageData = UIImageJPEGRepresentation(sourceImage,1.0);
    CGFloat sizeOriginKB = imageData.length / 1024.0;
    
    CGFloat resizeRate = 0.9;
    while (sizeOriginKB > maxSize && resizeRate > 0.1) {
        imageData = UIImageJPEGRepresentation(sourceImage,resizeRate);
        sizeOriginKB = imageData.length / 1024.0;
        resizeRate -= 0.1;
    }
    
    return imageData;
    
    
}

-(void)uploadImageWithUrl:(NSString *)url andParam:(NSDictionary *)param success:(LCSuccessHandler)success fail:(LCErrorHandler)fail
{
    //    [[MBProgressController sharedInstance] showWithText:@""];
    NSString *urlStr = [updateUrl stringByAppendingString:url];
    
    AFHTTPSessionManager *manage = [AFHTTPSessionManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    manage.requestSerializer = [AFHTTPRequestSerializer serializer];
    manage.requestSerializer.timeoutInterval = 30;
    
    if (TOKEN) {
        [manage.requestSerializer setValue:TOKEN forHTTPHeaderField:@"Token"];
    }
    
    [manage POST:urlStr parameters:param
        progress:^(NSProgress * _Nonnull uploadProgress) {
            //
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            NSLog(@"responseString:\n%@",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
            if ([dic[@"Success"] boolValue] == YES) {
                success(dic);
                
            }else{
                fail(dic[@"Msg"]? :@"");
                //                failture(@"failture");
            }
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            fail(@"网络请求失败");
        }];
}

@end
